package com.yatb.trac.controller.validator;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.validator.EmailValidator;
import org.apache.log4j.Logger;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.yatb.trac.pojo.Utenti;
import com.yatb.trac.pojo.condition.FindUtenteByUsername;
import com.yatb.trac.service.SearchService;
import com.yatb.trac.util.Container;

public class CreateUserValidator implements Validator {

	private Logger log = Logger.getLogger("tracsetup");
	private SearchService searchService;
	public boolean supports(Class<?> clazz) {
		return true;
	}

	public void validate(Object target, Errors errors) {
	}
	
	
	public void validateRequestParams(HttpServletRequest request,Object target,Errors errors){
		Utenti user = (Utenti) target;
		
		
		ValidationUtils.rejectIfEmpty(errors, "username", "",
				"Campo obbligatorio");
		ValidationUtils.rejectIfEmpty(errors, "password", "",
				"Campo obbligatorio");
		ValidationUtils
				.rejectIfEmpty(errors, "email", "", "Campo obbligatorio");
		EmailValidator emailValidator = EmailValidator.getInstance();
		if (!emailValidator.isValid(user.getEmail()) && !errors.hasErrors()) {
			errors.rejectValue("email", "", "Email inserita non valida!");
		}
//		HttpServletRequest request = (HttpServletRequest) Container.get();
//		log.debug("--------------------------------------------------------");
//		log.debug(request);
//		log.debug("--------------------------------------------------------");
		if(!errors.hasErrors()){
			Utenti[] utentis = getSearchService().find(new Utenti[0], new FindUtenteByUsername(request.getParameter("username")), Utenti.class);
			if(utentis!=null && utentis.length>0){
				errors.rejectValue("username", "", "Username già esistente");
			}

		}
		if (request != null) {
			String _page = request.getParameter("_page");
			if (_page != null && _page.equals("1")) {
				String[] progettiSelezionati = request.getParameterValues("progettiSelezionati");
				if (progettiSelezionati == null || progettiSelezionati.length==0) {
					errors.reject("",
							"Occorre assegnare almeno un progetto all'utente");
				}

			}
		}
		
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

}
